package db

import (
	"database/sql"
	"fmt"
	"sync"

	_ "github.com/go-sql-driver/mysql"
)

// 数据库连接池 单例模式 示例
// DB 数据库连接池
type DB struct {
	conn *sql.DB
}

var (
	instance *DB
	once     sync.Once
)

// GetDBInstance 获取数据库连接池实例
func GetInstance() *DB {
	once.Do(func() {
		conn, err := sql.Open("mysql", "root:12345678@tcp(127.0.0.1:3306)/test")
		if err != nil {
			panic(fmt.Sprintf("Failed to connect: %v", err))
		}

		// 测试连接是否有效
		if err = conn.Ping(); err != nil {
			conn.Close()
			panic(fmt.Sprintf("Failed to ping: %v", err))
		}
		// conn.SetMaxOpenConns(10)
		// conn.SetMaxIdleConns(5)
		instance = &DB{
			conn: conn,
		}
		fmt.Println("DB connection succeed")

	})
	return instance
}
